/** 
 * Project Name : cloudlead-utils-async 
 * File Name : AsyncTaskHandle.java 
 * Package Name : com.cloudlead.utils.async 
 * Date : 2014年7月16日下午4:26:39 
 * Copyright (c) 2014, cloudlead.com.cn All Rights Reserved. 
 * 
 */
package com.cloudlead.utils.async;

import java.util.Queue;
import java.util.concurrent.FutureTask;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 异步任务处理句柄
 * 
 * @Description 异步任务处理句柄
 * 
 * @date 2014年7月16日 下午4:26:39
 * @author 陆林(lulin@cloudlead-partners.com)
 * @version 2.0
 * @since 2.0
 */
public class AsyncTaskHandle<V> extends FutureTask<V> {

	final AsyncTask<V> task;

	public AsyncTaskHandle(AsyncTask<V> task) {
		super(task);
		this.task = task;
	}

	protected Queue<AsyncTaskCallback<V>> callbackQueue;

	/**
	 * 添加任务的回调函数
	 * 
	 * @param callback
	 *            回调函数
	 */
	public void addCallback(AsyncTaskCallback<V> callback) {
		if (null == callbackQueue) {
			callbackQueue = new LinkedBlockingQueue<AsyncTaskCallback<V>>();
		}
		callback.setSource(task);
		callbackQueue.add(callback);
	}

	/*
	 * @see java.util.concurrent.FutureTask#set(java.lang.Object)
	 */
	@Override
	protected void set(V v) {
		super.set(v);
		if (callbackQueue != null) {
			for (AsyncTaskCallback<V> callback : callbackQueue) {
				if (callback != null) {
					callback.onSuccess(v);
				}
			}
		}
	}

	/*
	 * @see java.util.concurrent.FutureTask#setException(java.lang.Throwable)
	 */
	@Override
	protected void setException(Throwable t) {
		super.setException(t);
		if (callbackQueue != null) {
			for (AsyncTaskCallback<V> callback : callbackQueue) {
				if (callback != null) {
					callback.onError(t);
				}
			}
		}
	}

}
